package com.example.filemonitor.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.filemonitor.book.entity.Book;
import com.example.filemonitor.book.mapper.BookMapper;
import com.example.filemonitor.book.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


import java.io.File;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {

    @Value("${monitor.rootPath}")
    String rootPath;


    @Override
    public void initDirFilePathToDB( ) {
        log.info("开始初始化book表。。。");
        //初始化rootpath下文件元数据到表
        //只有表为空才能初始化
        int count = this.count();
        Assert.isTrue(count ==0,"只有book表为空才能初始化");


        List<File> fileList = (List<File>) FileUtils.listFiles(new File(rootPath),
                new String[]{"ppt","pptx","doc","docx","xlsx","xls","pdf"}, true);
        log.info("找到{}个文件。。。",fileList.size());

        fileList.stream().forEach(file -> {
           log.info("发现文件：{}",file.getAbsolutePath());

            Book book = new Book();

            book.setTitle(file.getName());
            book.setDescription(file.getName());
            book.setPath(file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(rootPath)+rootPath.length()));

            Date now = new Date();
            book.setCreateTime(now);
            book.setUpdateTime(now);

            log.info("book:{}" ,book);

            this.save(book);

        });

        log.info("init db done!");

    }

    @Override
    public Book getByPath(String absPath) {
        String relativePath = absPath.substring(absPath.indexOf(rootPath)+rootPath.length());
        Book book = baseMapper.selectOne(new QueryWrapper<Book>().eq("path", relativePath));
        return book;
    }


}
